from fastapi import APIRouter, Depends
from app.response import success, fail
from app.database import get_db
from pydantic import BaseModel, Field
from app.cache import get_redis

import json

test_router = APIRouter(prefix="/api/test")


# /api/test/test1?cat=图书
# /api/test/type/图书
@test_router.get("/test1", tags=["查询接口样例"])
def test1( cat: str,  db=Depends(get_db) ):
    data = db.getOne(
        "select sum(price) as c from `order` where `category`='%s'" % cat
    )
    return success("OK", data)


@test_router.get("/type/{name}", tags=["查询接口样例"])
def test2( name: str,  db=Depends(get_db) ):
    data = db.getOne(
        "select sum(price) as c from `order` where `category`='%s'" % cat
    )
    return success("OK", data)


class UserInfo(BaseModel):
    username: str = Field(min_length=6, max_length=20)
    password: str = Field(patten="\d{6,20}")
    age: int

@test_router.post("/test3")
def test3(redis = Depends(get_redis)):
    redis.set("a", 100);

    return success("OK", redis.get("a"))


@test_router.get("/dbtest1")
def test4(page:int=1, limit:int=10, db=Depends(get_db) ):

    offset = (page-1) * limit

    result = db.getOne("select count(*) as cnt from person where 1")
    total  = result['cnt']

    sql = "select * from person where 1 limit %d, %d" % (offset, limit)
    persons = db.getAll(sql)

    return success("OK", {"total":total, "rows":persons})

@test_router.get("/person/del")
def test5(pid:int, db=Depends(get_db)):
    one = db.getOne("select * from person where id=%d" % pid)
    if one!=None:
        # 判断该用户是否能删除， role = 9 表示管理员不能删除
        # if one['role'] == 9:
        #     return fail("不允许删除管理员")
        sql = "delete from person where id=%d" % pid
        db.query(sql)
        return success("删除成功")
    else:
        return fail("数据不存在")
    
@test_router.get("/redistest")
def test6(redis = Depends(get_redis)):
    # json.dumps(obj)
    # json.loads("{}")
    d = {"x":100, "y":200}
    redis.set("count", json.dumps(d))
    return success("操作成功", json.loads(redis.get("count")))